// src/features/workspaces/api/use-join.ts
import {useCallback, useMemo, useState} from "react";
import {MARK_DATA_URL} from "@/lib/social/constants";
import {v4 as uuidv4} from 'uuid';
import {useCurrentUser} from "@/hooks/use-current-user";
// import crypto from "crypto";

type Options = {
    onSuccess?: (workspaceId: string) => void
    onError?: (error: Error) => void
    onSettled?: () => void
    throwError?: boolean
}

type RequestType = {
    workspaceId: string
    userId: string
    joinCode: string
} | null

type ResponseType = {
    id: string
} | null

// client
export const useJoin = () => {
    // create db workspace
    // const user = useCurrentUser()

    const [data, setData] = useState<RequestType>(null)
    const [error, setError] = useState<Error | null>(null)
    const [status, setStatus] =
        useState<"success" | "error" | "settled" | "pending" | null>()

    // const [isPending, setIsPending] = useState<boolean>(false)
    // const [isSuccess, setIsSuccess] = useState<boolean>(false)
    // const [isSettled, setIsSettled] = useState<boolean>(false)
    // const [isError, setIsError] = useState<boolean>(false)

    const isPending = useMemo(() => status === 'pending', [status])
    const isSuccess = useMemo(() => status === 'success', [status])
    const isSettled = useMemo(() => status === 'settled', [status])
    const isError = useMemo(() => status === 'error', [status])

    const mutate = useCallback(async (values: RequestType, options?: Options) => {
        try {
            setData(null)
            setError(null)
            setStatus('pending')

            const w_res = await fetch(
                // `${MARK_DATA_URL}/workspaces?joinCode=${values?.joinCode}`
                `/api/workspaces?joinCode=${values?.joinCode}`
            )
            const w = await w_res.json()
            if (w.length === 0 || !w)
                throw new Error(`Workspace don't exist or joinCode error`)

            // 邀请进房间
            const response1 = await fetch(
                // `${MARK_DATA_URL}/members?workspaceId=${values?.workspaceId}&userId=123456`
                // `/api/members?workspaceId=${values?.workspaceId}`
                `/api/members?workspaceId=${values?.workspaceId}&userId=${values?.userId!}`
            )
            const members = await response1.json()
            // if (members) { // json-server返回的是数组, 所以永远非null
            //     throw new Error('Already an active member of this workspace')
            // }
            console.log('use join get members', members)
            if (members.length !== 0)
                throw new Error('Already an active member of this workspace')

            // const id = uuidv4()
            const response = await fetch(
                // `${MARK_DATA_URL}/members`, {
                `/api/members`, {
                    method: "POST",
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        workspaceId: values?.workspaceId,
                        // id,
                        // userId: user?.id,
                        role: "member"
                    })
                }
            )

            if (response.ok) options?.onSuccess?.(values?.workspaceId!)
            setStatus('success')
            return values?.workspaceId!
        } catch (error) {
            setStatus('error')
            options?.onError?.(error as Error)
            if (options?.throwError) throw error
        } finally {
            setStatus("settled")
            options?.onSettled?.()
        }
    }, []);

    return {
        mutate, error, isPending, isSuccess, isSettled, isError
    }
}